<?php
class PiscesAction extends LtAction
{
	public function __construct()
	{
		parent::__construct();
	}
	
	public function beforeExecute()
	{
		$this->config = C('LtConfig');
		$this->data['baseurl']	= $this->config->get('baseurl');
		$this->data['pisces'] = $this->config->get('pisces');
		$this->data['template'] = Util::loadSetting('template');
		if(empty($this->data['template']))
		{
			$this->data['template'] = 'default';
		}
		$this->data['site'] = Util::loadSetting('site');
	}
	
	protected function writeResponse()
	{
		switch ($this->responseType)
		{
			case 'tpl':
				if (empty($this->template))
				{
					$this->template = strtolower($this->context->uri["module"] . "/" . $this->context->uri["action"]);
				}
				break;
		}
		parent::writeResponse();
	}
	
	public function parseDtds($module,$action)
	{
		$appDir		= $this->app_dir;
		$appName	= $this->app_name;
		
		$dtdsFile	= $appDir.'/dtds/'.strtolower($module).'.dtds.php';
		if(!is_file($dtdsFile))
		{
			return false;
		}
		include($dtdsFile);
		if(empty($dtds) || !array_key_exists($action,$dtds))
		{
			return false;
		}
		
		$tmp	= $dtds[$action];
		foreach($tmp as $k=>$v)
		{
			if(array_key_exists('equal_to',$v['value']))
			{
				if(strtoupper($v['value']['equal_to']['from'])=='POST')
				{
					$v['value']['equal_to']	= $this->context->post($v['value']['equal_to']['name']);
				}
			}
			$this->dtds[$k] = new LtValidatorDtd($v['name'],$v['value'],$v['message']);
		}
	}
	
	public function getValidData()
	{
		if(empty($this->dtds))
		{
			return false;
		}
		$data	= array();
		$keys	= array_keys($this->dtds);
		foreach($keys as $k)
		{
			$v		= $this->context->request($k);
			
			$tmp	= explode('#',$k);
			$len	= count($tmp);
			if($len==1)
			{
				$data[$tmp[0]]	= $v;
			}
			else
			{
				$d		= &$data;
				for($i=0;$i<$len-1;$i++)
				{
					if(!array_key_exists($tmp[$i], $d))
					{
						$d[$tmp[$i]]	= array();
					}
					$d				= &$d[$tmp[$i]];
				}
				$d[$tmp[$len-1]]	= $v;
			}
		}
		return $data;
	}
	
	public function getPage()
	{
		$page 		= $this->context->get('p');
		$page 		= max(intval($page), 1);
		if($page<1)
		{
			$page	= 1;
		}
		return $page;
	}
	
	public function getIp()
	{
		return $this->context->server('REMOTE_ADDR');
	}
	
	protected function redirect($url)
	{
		echo '<script language="javascript">document.location="'.$url.'";</script>';
		exit;
	}
}
